<template>
  <div class="permissions">
    <el-card>
      <el-row :gutter="20">
        <el-col :span="3">
          <el-input
            v-model="query.title"
            placeholder="根据用户名搜索"
          ></el-input>
        </el-col>
        <el-col :span="1">
          <el-button size="mini" @click="query.title = ''">清除</el-button>
        </el-col>
        <el-col :span="1">
          <el-button
            type="primary"
            size="mini"
            class="search"
            @click="gitpermissions"
            >搜索</el-button
          >
        </el-col>
        <el-col :span="2" :offset="16">
          <el-button
            type="success"
            size="mini"
            icon="el-icon-edit"
            @click="addpermissions"
            >新增权限组</el-button
          >
        </el-col>
      </el-row>
      <!-- 提示消息 -->
      <el-alert
        :title="`共${total}条数据`"
        type="info"
        class="alert"
        :closable="false"
        show-icon
      ></el-alert>
      <!-- 表格 -->
      <el-table style="width: 100%" stripe border :data="list">
        <el-table-column type="selection" width="280"></el-table-column>
        <el-table-column label="用户名" prop="title"></el-table-column>
        <el-table-column label="日期" width="550" prop="create_date" sortable>
          <template v-slot="{ row }">{{
            row.create_date | relativeTime
          }}</template>
        </el-table-column>
        <el-table-column label="操作" width="150" class="lastbtn">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              circle
              class="lastbtn"
              @click="change(scope.row)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              circle
              class="lastbtn"
              @click="remove(scope.row.id)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="query.page"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="query.pagesize"
        layout=" sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <!-- 添加弹出框 -->
    <el-dialog :visible.sync="dialogVisible" width="50%" @close="addclose">
      <template slot="title" class="dialogtitle">创建权限组</template>
      <el-form
        style="width: 400px; margin-left: 120px"
        :model="form"
        :rules="rules"
        ref="addRormref"
      >
        <el-form-item label="用户名" label-width="120px" prop="name">
          <el-input class="dialoginput" v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="权限分配" label-width="120px">
          <!-- 添加树形图 -->
          <el-tree
            show-checkbox
            :data="addlist"
            :props="defaultProps"
            node-key="id"
            highlight-current
            :default-checked-keys="defauTree"
            :default-expanded-keys="[1]"
            ref="treeRef"
          ></el-tree>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="sureadd">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加弹出框 -->
    <!-- 修改弹出框 -->
    <el-dialog title="提示" :visible.sync="dialogalter" width="50%">
      <template slot="title" class="dialogtitle">修改权限组</template>
      <el-form
        style="width: 400px; margin-left: 120px"
        :model="editForm"
        :rules="editFormrules"
        ref="editref"
      >
        <el-form-item label="用户名" label-width="120px" prop="title">
          <el-input class="dialoginput" v-model="editForm.title"></el-input>
        </el-form-item>
        <el-form-item label="权限分配" label-width="120px">
          <!-- 编辑树状图 -->
          <el-tree
            show-checkbox
            :data="changetreelist"
            :props="changeProps"
            node-key="id"
            highlight-current
            :default-checked-keys="changedefauTree"
            :default-expanded-keys="[1]"
            ref="changetreeRef"
          ></el-tree>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogalter = false">取 消</el-button>
        <el-button type="primary" @click="surechange()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改弹出框 -->
  </div>
</template>

<script>
import {
  gitpermissions,
  getChaiDanLieBiao,
  addpermissions,
  detail,
  remove,
  change
  // detail
} from '@/api/permissions.js'
// import adddialog from './components/adddialog.vue'
export default {
  name: 'permissions',
  components: {},
  props: {},
  data() {
    return {
      // input: '', // input输入框绑定值
      query: {
        // 请求数据
        page: 1, // 当前页数
        pagesize: 2, // 页尺寸 当前显示多少条
        title: '' // 关键字
      },
      list: [], // 存储数据
      total: 0,
      dialogVisible: false, // 添加的弹出框
      dialogalter: false, // 修改弹出框

      // 验证规则
      rules: {
        name: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ]
      },
      // -------------增加弹框数据
      addlist: [], // 添加tree数据列表
      defauTree: [], // 添加tree默认选中数组
      defaultProps: {
        children: 'childs',
        label: 'title'
      },
      // 增加表单
      form: {
        name: ''
      },
      // --------------------修改数据
      editForm: {}, // 修改的表单
      // 验证规则
      editFormrules: {
        title: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ]
      },
      changetreelist: [], // 修改树状图数据
      changeProps: {
        // 修改树状图配置
        children: 'childs',
        label: 'title'
      },
      changedefauTree: [] // 修改树默认选中
    }
  },
  computed: {},
  watch: {},
  created() {
    this.gitpermissions()
  },
  mounted() {},
  methods: {
    // 获取列表数据
    async gitpermissions() {
      const { data } = await gitpermissions(this.query)
      // this.total = data.counts
      console.log(data)
      this.total = data.counts
      this.list = data.list
      console.log(this.list)
    },
    // 分页
    // 点击下拉条变化
    handleSizeChange(val) {
      this.query.pagesize = val
      this.gitpermissions()
    },
    // 点击页面变化
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      this.query.page = val
      this.gitpermissions()
    },
    // 添加-----------点击添加权限 获取树形图数据
    async addpermissions() {
      try {
        this.dialogVisible = true
        // 获取数据
        this.addlist = []
        const { data } = await getChaiDanLieBiao()
        console.log(data)

        data.forEach((item) => {
          item.childs.forEach((item1) => {
            item1.childs = item1.points
          })
        })
        const reset = {
          id: 1,
          title: '系统菜单和页面权限点',
          childs: [...data]
        }

        this.addlist.push(reset)
        console.log(this.addlist)
      } catch (error) {
        console.log(error)
      }
    },
    //  -------点击确认添加按钮
    sureadd() {
      // ------表单验证validate
      this.$refs.addRormref.validate(async (valid) => {
        if (!valid) {
          this.$message('表单错误')
          return
        }
        // 调接口 添加数据
        this.defauTree = [...this.$refs.treeRef.getCheckedKeys()]
        // console.log(this.$refs.treeRef)
        // console.log(this.defauTree)
        this.defauTree.splice(0, 1)
        // console.log(this.defauTree)
        try {
          await addpermissions({
            title: this.form.name,
            permissions: this.defauTree
          })
          this.$message.success('添加成功!')
          // 更新视图
          this.gitpermissions()
        } catch (error) {
          this.$message.error('添加失败')
        }

        this.dialogVisible = false
      })
    },
    // -----------------新增按钮的关闭事件
    addclose() {
      // 清空表单
      console.log(this.list)

      this.$refs.addRormref.resetFields()
      this.defauTree = []
    },
    // --------点击修改按钮
    async change(row) {
      this.dialogalter = true
      // 获取树状图的结构数据
      this.changetreelist = []
      const { data } = await getChaiDanLieBiao()
      data.forEach((item) => {
        item.childs.forEach((item1) => {
          item1.childs = item1.points
        })
      })
      const reset = {
        id: 1,
        title: '系统菜单和页面权限点',
        childs: [...data]
      }
      this.changetreelist.push(reset)
      // console.log(this.changetreelist)

      // 渲染完数据后调用接口 获取点击的数据
      // console.log(row)
      try {
        const { data } = await detail(row)
        this.editForm = data
        // console.log(this.editForm)
        this.changedefauTree = data.permissions
      } catch (error) {
        this.$message('获取数据失败')
      }
    },
    // -------------点击修改确定建 修改数据
    surechange() {
      // 进行表单验证
      this.$refs.editref.validate(async (vaile) => {
        if (!vaile) {
          return this.$message.error('表单错误')
        }
        console.log(this.editForm.permissions)
        try {
          // 修改树的选中
          this.changedefauTree = this.$refs.changetreeRef.getCheckedKeys()
          await change({
            id: this.editForm.id,
            title: this.editForm.title,
            permissions: this.changedefauTree // 默认选中的树节点 getCheckedKeys
          })
          // console.log(data)
          this.gitpermissions()

          this.dialogalter = false
        } catch (error) {
          this.$message.error('修改失败')
        }
      })
    },

    // 删除
    async remove(id) {
      const res = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)
      // console.log(res)
      if (res !== 'confirm') {
        return this.$message.info('您取消了操作')
      }
      try {
        await remove(id)
        this.gitpermissions()
        this.$message.success('删除成功')
      } catch (error) {
        this.$message.error('删除失败')
      }
    }
  }
}
</script>

<style scoped lang="less">
.permissions {
  padding: 10px;
}
/deep/.el-input__inner,
.el-button {
  height: 32px !important;
  // line-height: px;
}
.search {
  margin-left: 15px;
}
.alert {
  margin-top: 20px;
}
.lastbtn {
  height: unset !important;
}
/deep/.el-dialog__header {
  background-color: #409eff;
  // height: 54px;
  color: #fff;
  font-size: 20px;
}
.dialoginput {
  width: 280px;
}
</style>
